<?php
namespace app\home\controller;

use app\common\component\user\UserModel;

class Promotion extends ControllerBase {
    public function index() {
    	$this -> checkLogin();
		
		$USER_REWARD_LAYERS_JSON = json_decode(getParam('USER_REWARD_LAYERS_JSON'), true);
    	$this -> view -> assign('layers', $USER_REWARD_LAYERS_JSON);

		$promotions = [];
		$field = 'user_id, promotion_id, username, realname, phone, createtime';
		$resultUsers = UserModel::where('promotion_id', \think\Session::get('user_id')) -> field($field) -> select();
		if($resultUsers) {
			$promotion_ids = '';
			foreach($resultUsers as $resultUser) {
				$promotions[1][] = $resultUser -> toArray();
				$promotion_ids .= $resultUser -> user_id . ',';
			}
			$promotion_ids = substr($promotion_ids, 0, -1);
			
			$layersNum = count($USER_REWARD_LAYERS_JSON);
			for($i = 2;$i <= $layersNum;$i++) {
				$promotionUsers = UserModel::where('promotion_id', 'in', $promotion_ids) -> field($field) -> select();
	
				$promotion_ids = '';
				if($promotionUsers) {
					foreach($promotionUsers as $promotionUser) {
						$promotions[$i][] = $promotionUser -> toArray();
						$promotion_ids .= $promotionUser -> user_id . ',';
					}
					$promotion_ids = substr($promotion_ids, 0, -1);
				} else {
					break;
				}
			}
		}

    	$this -> view -> assign('promotions', $promotions);
    	return $this -> view -> fetch();
    }

    public function register() {
    	return $this -> view -> fetch();
    }

	public function down() {
		$this -> view -> assign('users', UserModel::where('promotion_id', \think\Session::get('user_id')) -> order('status DESC, user_id DESC') -> paginate(10, true));
		return $this -> view -> fetch();
	}
}
?>